/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import { AppRegistry, DeviceEventEmitter, AsyncStorage } from 'react-native';
import NetworkUtil from './src/utils/NetworkUtil';
import { Provider } from 'react-redux';
import Toast from 'react-native-root-toast';
import PropTypes from 'prop-types';
import configureStore from './src/store/configure-store';
import { toastShort, toastLong } from './src/utils/Toast';
import RouterConfig from './src/router';
import { ERROR_HANDLE_TOAST } from './src/constants/Global';

const store = configureStore();

if (!__DEV__) {
  global.console = {
    info: () => {},
    log: () => {},
    warn: () => {},
    error: () => {},
  };

  //捕捉js错误
  // global.ErrorUtils.setGlobalHandler((err) => {
  //   console.log('ErrorUtils', err)
  // });
}

export default class MainApp extends Component {
  static propTypes = {
    navigation: PropTypes.object,
  };

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    NetworkUtil.addChangeEventListener();  //监听网络状态
    global.toast = toastShort; //toast 可暴露给全局方便调用；
    global.toastShort = toastShort;
    global.toastLong = toastLong;
    //token 存在，获取用户信息
    AsyncStorage.multiGet(['token', 'userId'], (error, data) => {
      if (data[0][1] && data[1][1]) {
        //登录状态下
        global.token = data[0][1];
        global.userId = data[1][1];
      } else {
        global.token = '';
        global.userId = '';
      }
    });

    this.errorHandlerEmitter = DeviceEventEmitter.addListener(
      ERROR_HANDLE_TOAST,
      msg => {
        Toast.show(msg, {
          position: Toast.positions.TOP,
        });
      },
    );

    //codePush 预留
  }

  componentWillUnmount() {
    this.errorHandlerEmitter.remove();
  }

  render() {
    const { navigation } = this.props;

    return (
      <Provider store={store}>
        <RouterConfig navigation={navigation} />
      </Provider>
    );
  }
}
/* eslint-disable */
console.disableYellowBox = true;

AppRegistry.registerComponent('RnProject', () => MainApp);
